# -*- coding: utf-8 -*-

import datetime

from mole import route
from mole import request
from mole import response,abort,redirect
from mole import redirect
from mole.template import jinja2_template as render_template
from mole.common import HTTPResponse
from mocrud.utils import PaginatedQuery
from mocrud.admin import admin
from mocrud.utils import flash
from mocrud.db import db
from wtforms import Form, TextField, DateField, validators
from wtforms.validators import ValidationError

from models import BookForBorrow
from models import BorrowRecord,Book,Reader

@route('/admin/bookM',name='bookM')
def homepage():
    from mocrud.admin import admin
    return render_template('admin/model_grup.html',
        panels=admin.get_panels(),
        model_grup = 'default',
        model_admins=admin.get_grup_admins('default'),
        **admin.template_helper.get_helper_context()
    )
    
@route('/',name='borrow_index')
def index():
    ordering = request.params.get('ordering') or ''
    
    self = admin.get_admin_for(BookForBorrow)
    query = self.get_query()
    query = self.apply_ordering(query, ordering)
    filter_form, query, cleaned, field_tree = self.process_filters(query)
    pq = PaginatedQuery(query, 20)
    
    new_list = BookForBorrow.select().order_by( BookForBorrow.purchaseDate.desc() ).limit(10)
    top_list = BookForBorrow.select().order_by( BookForBorrow.owned_count.desc() ).limit(10)
    
    return render_template('borrow_index.html',
        model_admin=self,
        query=pq,
        ordering=ordering,
        filter_form=filter_form,
        field_tree=field_tree,
        active_filters=cleaned,
        new_list = new_list,
        top_list = top_list,
        **self.get_extra_context()
    )
    
@route('/borrow/:pk/',name='admin.bookforborrow_borrow',method=['GET', 'POST'])
def borrow(pk):
    self = admin.get_admin_for(BookForBorrow)
    
    try:
        instance = self.get_object(pk)
    except self.model.DoesNotExist:
        abort(404)

    #Form = self.get_edit_form(instance)
    class brForm(Form):
        name = TextField(u'请填写您的姓名', validators=[validators.Required()])
        plan_time = DateField(u'预计归还日期',default=datetime.datetime.now, validators=[validators.Required()])

    if request.method == 'POST':
        form = brForm(request.forms)
        if form.validate():
            m_name = form.name.data.lstrip().rstrip()
            m_plan_time = form.plan_time.data
            m_book_id = request.forms["id"]
            if len(m_name)>10:
                flash(u'姓名不合法', 'error')
            elif m_plan_time<=datetime.datetime.now().date():
                flash(u'日期不能小于或等于当前时间', 'error')
            elif not m_book_id:
                flash(u'对象不存在', 'error')
            else:
                try:
                    book = instance#Book.get(Book.id==long(m_book_id))
                    with db.database.transaction():
                        newbr = BorrowRecord()
                        newbr.book = book
                        try:
                            reader = Reader.get(Reader.name==m_name)
                        except Reader.DoesNotExist:
                            reader = Reader(name=m_name)
                            reader.save()
                        newbr.owner = reader
                        newbr.plan_time = m_plan_time
                        newbr.save()
                        
                        book.owned = True
                        book.owned_count =  book.owned_count + 1
                        book.save()
                except:
                    import traceback
                    traceback.print_exc()
                    flash(u'借阅失败，请稍后重试！', 'error')
                else:
                    flash(u'借阅 %s 成功！请记住此书序列号 "%s"，还书是要填写的哟' %(book,book.seq), 'success')
                    return redirect('/')
    else:
        form = brForm()
        
    new_list = BookForBorrow.select().order_by( BookForBorrow.purchaseDate.desc() ).limit(10)
    top_list = BookForBorrow.select().order_by( BookForBorrow.owned_count.desc() ).limit(10)

    return render_template('borrow.html',
        model_admin=self,
        instance=instance,
        form=form,
        new_list = new_list,
        top_list = top_list,
        **self.get_extra_context()
    )

@route('/revert/:pk/',name='admin.bookforborrow_revert',method=['GET', 'POST'])
def revert(pk):
    self = admin.get_admin_for(BookForBorrow)
    
    try:
        instance = self.get_object(pk)
    except self.model.DoesNotExist:
        abort(404)

    class rvForm(Form):
        seq = TextField(u'请填写书的序列号', validators=[validators.Required()])

    if request.method == 'POST':
        form = rvForm(request.forms)
        if form.validate():
            m_seq = form.seq.data.lstrip().rstrip()
            m_book_id = request.forms["id"]
            if not m_book_id:
                flash(u'对象不存在', 'error')
            else:
                try:
                    book = BookForBorrow.get( (BookForBorrow.id==long(m_book_id) ) & (BookForBorrow.seq==m_seq) )
                except BookForBorrow.DoesNotExist:
                    flash(u'此序列号的图书不存在，请核实！', 'error')
                else:
                    try:
                        with db.database.transaction():
                            oldbr = BorrowRecord.get( (BorrowRecord.book==book) & (BorrowRecord.revert_flag==False) )
                            oldbr.revert_flag = True
                            oldbr.revert_time = datetime.datetime.now()
                            oldbr.save()
                            
                            book.owned = False
                            book.save()
                    except:
                        import traceback
                        traceback.print_exc()
                        flash(u'归还失败，请稍后重试！', 'success')
                    else:
                        flash(u'归还 %s 成功' %book, 'success')
                        return redirect('/')
    else:
        form = rvForm()
        
    new_list = BookForBorrow.select().order_by( BookForBorrow.purchaseDate.desc() ).limit(10)
    top_list = BookForBorrow.select().order_by( BookForBorrow.purchaseDate.desc() ).limit(10)

    return render_template('revert.html',
        model_admin=self,
        instance=instance,
        form=form,
        new_list = new_list,
        top_list = top_list,
        **self.get_extra_context()
    )
    
    
#    from mocrud.admin import admin
#    return jinja2_template('borrow_index.html',
#        panels=admin.get_panels(),
#        model_grup = 'default',
#        model_admins=admin.get_grup_admins('default'),
#        **admin.template_helper.get_helper_context()
#    )